package org.itzixi.controller;


import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.itzixi.RedisKeyConstant;
import org.itzixi.excptions.GraceException;
import org.itzixi.grace.result.GraceJSONResult;
import org.itzixi.grace.result.ResponseStatusEnum;
import org.itzixi.service.ChatMessageService;
import org.itzixi.utils.PagedGridResult;
import org.itzixi.utils.RedisOperator;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/chat")
@Slf4j
public class ChatController {

    @Resource
    private RedisOperator redis;

    @Resource
    private ChatMessageService chatMessageService;


    @PostMapping("/getMyUnReadCounts")
    public GraceJSONResult getMyUnReadCounts(String myId)  {
        String key = String.join(StrUtil.COLON, RedisKeyConstant.CHAT_MSG_LIST, myId);
        Map<Object, Object> hgetall = redis.hgetall(key);
        return GraceJSONResult.ok(hgetall);
    }


    @PostMapping("/clearMyUnReadCounts")
    public GraceJSONResult clearMyUnReadCounts(String myId, String oppositeId)  {
        String key = String.join(StrUtil.COLON, RedisKeyConstant.CHAT_MSG_LIST, myId);
        redis.setHashValue(key, oppositeId, "0");
        return GraceJSONResult.ok();
    }

    @PostMapping("/list/{senderId}/{receiverId}")
    public GraceJSONResult list(@PathVariable("senderId") String senderId, @PathVariable("receiverId") String receiverId,
                                Integer page, Integer pageSize)  {
        if (StrUtil.isBlank(senderId) || StrUtil.isBlank(receiverId)){
            GraceException.display(ResponseStatusEnum.SYSTEM_ERROR_NOT_BLANK);
        }
        if (page == null || page == 0)
            page = 1;
        if (pageSize == null || pageSize == 0)
            page = 20;
        PagedGridResult pagedGridResult = chatMessageService.queryChatMsgList(senderId, receiverId, page, pageSize);
        return GraceJSONResult.ok(pagedGridResult);
    }

    @PostMapping("/signRead/{msgId}")
    public GraceJSONResult signRead(@PathVariable("msgId") String msgId)  {
        if (StrUtil.isBlank(msgId)){
            GraceException.display(ResponseStatusEnum.SYSTEM_ERROR_NOT_BLANK);
        }
        chatMessageService.updateMsgSignRead(msgId);
        return GraceJSONResult.ok();
    }


}

